package com.cszy.yydqbfq.ui.activity

import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.SeekBar
import androidx.lifecycle.lifecycleScope
import com.airbnb.lottie.model.content.RoundedCorners
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.cszy.yydqbfq.R
import com.cszy.yydqbfq.databinding.ActivityPlayDetailBinding
import com.cszy.yydqbfq.base.BaseEvent
import com.cszy.yydqbfq.base.BaseVMActivity
import com.cszy.yydqbfq.bean.Song
import com.cszy.yydqbfq.common.AppConstants.PLAY_STAUS_CHANGE
import com.cszy.yydqbfq.common.EventUtils
import com.cszy.yydqbfq.common.PlaylistRepository
import com.cszy.yydqbfq.dialog.BottomPopupWithGeDanRecycler
import com.cszy.yydqbfq.dialog.BottomPopupWithRecycler
import com.cszy.yydqbfq.ext.clickWithTrigger
import com.cszy.yydqbfq.ext.toast
import com.cszy.yydqbfq.viewmodel.MainViewModel
import com.hlyj.http.ad.NewGroMoreFeedAdManager
import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener
import com.hnyyac.ad.mds.utils.BaseAdConstants
import com.lzx.starrysky.OnPlayProgressListener
import com.lzx.starrysky.OnPlayerEventListener
import com.lzx.starrysky.SongInfo
import com.lzx.starrysky.StarrySky
import com.lzx.starrysky.control.RepeatMode.Companion.REPEAT_MODE_NONE
import com.lzx.starrysky.control.RepeatMode.Companion.REPEAT_MODE_ONE
import com.lzx.starrysky.control.RepeatMode.Companion.REPEAT_MODE_SHUFFLE
import com.lzx.starrysky.manager.PlaybackStage
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

class PlayDetailActivity : BaseVMActivity<MainViewModel, ActivityPlayDetailBinding>(),
    OnPlayerEventListener, OnPlayProgressListener, IAdViewListener {
    var type_proces: String? = null //功能入口类型
    private var progressJob: Job? = null
    private var songInfo: MutableList<SongInfo>? = null
    private var position: Int = 0;
    private var newGromoreFeedAd: NewGroMoreFeedAdManager? = null
    override fun initView(savedInstanceState: Bundle?) {
        mBinding.headTitle.headBack.setImageResource(R.mipmap.ic_play_back)
    }

    override fun initData() {
        type_proces = "第一次插屏"
        AdManager.loadChapin_nocache(
            this,
            21,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    newGromoreFeedAd = NewGroMoreFeedAdManager(
                        this@PlayDetailActivity,
                        BaseAdConstants.FEEDAD_Id,
                        mBinding?.frameLayoutBannerDetail,
                        22
                    )
                    newGromoreFeedAd?.loadAd()
                }
            })
        songInfo = intent.getParcelableArrayListExtra<SongInfo>("MUSIC_LIST")
        position = intent.getIntExtra("CURRENT_POSITION", 0)

        Log.e("PlayDetailActivity", "songInfo:" + songInfo.toString())
        StarrySky.with().playMusic(songInfo as MutableList<SongInfo>, position)

        Glide.with(this)
            .load(songInfo?.get(position)?.songCover)
            .placeholder(R.mipmap.ic_playdetail_out)
            .error(R.mipmap.ic_playdetail_out)
            .apply(RequestOptions.circleCropTransform()) // 关键代码：圆形裁剪
            .into(mBinding.ivDetail)

        setRepeatMode()
    }

    override fun onResume() {
        super.onResume()
        var isplay = StarrySky.with().isPlaying()
        if (isplay) {
            mBinding.ivBofangDetail.setImageResource(R.mipmap.ic_pause)
        } else {
            mBinding.ivBofangDetail.setImageResource(R.mipmap.ic_bofang_detail)
        }
        var songInfo = StarrySky.with().getNowPlayingSongInfo()
        mBinding.headTitle.headCenterTitle.text = songInfo?.songName
        mBinding.tvAuthorName.text = songInfo?.artist
        mBinding.tvSongName.text = songInfo?.songName
    }

    override fun initListener() {
        //返回
        mBinding.headTitle.headBack.setOnClickListener {
            finish()
        }


        mBinding.headTitle.headCenterTitle.setTextColor(resources.getColor(R.color.title_color))


        mBinding.ivPlayMoshi.clickWithTrigger {
            changeRepeatMode()
        }

        mBinding.ivPlayDetail.setOnClickListener {
            BottomPopupWithRecycler(this, songInfo!!).show(it, position)
        }

        //播放状态
        mBinding.ivBofangDetail.setOnClickListener {
            if (StarrySky.with().isPlaying()) {
                StarrySky.with().pauseMusic()
            } else {
                StarrySky.with().restoreMusic()
            }
        }


        //上一曲
        mBinding.ivPlayShang.setOnClickListener {
            StarrySky.with().skipToNext()
        }
        //下一曲
        mBinding.ivPlayXia.setOnClickListener {
            StarrySky.with().skipToPrevious()
        }

        // 1. 初始化 SeekBar
        mBinding.progressSeekbar.setOnSeekBarChangeListener(object :
            SeekBar.OnSeekBarChangeListener {
            // 获取当前播放位置（毫秒）
            val currentPosition = StarrySky.with().getPlayingPosition()

            // 获取音频总时长（毫秒）
            val duration = StarrySky.with().getDuration()

            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    // 用户拖动时实时显示时间（但不立即跳转）
                    mBinding.tvCurrentTime.text = formatTime(progress * 1000L)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {
                // 开始拖动时暂停进度监听（避免冲突）
                progressJob?.cancel() // 用户拖动时暂停自动更新
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
                // 拖动结束时跳转到指定位置
                StarrySky.with().seekTo(seekBar.progress * 1000L)
                startProgressUpdates() // 恢复更新
            }
        })

    }

    // 启动协程监听进度
    private fun startProgressUpdates() {
        progressJob?.cancel() // 确保只有一个协程在运行
        progressJob = lifecycleScope.launch {
            while (isActive) {
                updateProgress()
                delay(1000) // 每秒更新一次
            }
        }
    }

    private fun updateProgress() {
        val currPos = StarrySky.with().getPlayingPosition()
        val duration = StarrySky.with().getDuration()

        runOnUiThread {
            mBinding.tvCurrentTime.text = formatTime(currPos)
            mBinding.tvCountTime.text = formatTime(duration)
            mBinding.progressSeekbar.max = (duration / 1000).toInt()
            mBinding.progressSeekbar.progress = (currPos / 1000).toInt()
        }
    }

    private fun setRepeatMode() {
        currentMode = StarrySky.with().getRepeatMode().repeatMode
        when (currentMode) {
            REPEAT_MODE_NONE -> {
                mBinding.ivPlayMoshi.setImageResource(R.mipmap.ic_liebiao_xunhuan)
            }

            REPEAT_MODE_ONE -> {
                mBinding.ivPlayMoshi.setImageResource(R.mipmap.ic_liebiao_only)
            }

            REPEAT_MODE_SHUFFLE -> {
                mBinding.ivPlayMoshi.setImageResource(R.mipmap.ic_liebiao_random)
            }

            else -> {
                mBinding.ivPlayMoshi.setImageResource(R.mipmap.ic_liebiao_xunhuan)
            }
        }
    }

    var currentMode: Int = REPEAT_MODE_NONE
    private fun changeRepeatMode() {
        // 修复后的代码应该如下：
        currentMode = StarrySky.with().getRepeatMode().repeatMode
        when (currentMode) {
            0 -> {
                StarrySky.with().setRepeatMode(REPEAT_MODE_ONE, true)
                mBinding.ivPlayMoshi.setImageResource(R.mipmap.ic_liebiao_only)
            }

            REPEAT_MODE_NONE -> {
                StarrySky.with().setRepeatMode(REPEAT_MODE_ONE, true)
                mBinding.ivPlayMoshi.setImageResource(R.mipmap.ic_liebiao_only)
            }

            REPEAT_MODE_ONE -> {
                StarrySky.with().setRepeatMode(REPEAT_MODE_SHUFFLE, true)
                mBinding.ivPlayMoshi.setImageResource(R.mipmap.ic_liebiao_random)
            }

            REPEAT_MODE_SHUFFLE -> {
                StarrySky.with().setRepeatMode(REPEAT_MODE_NONE, true)
                mBinding.ivPlayMoshi.setImageResource(R.mipmap.ic_liebiao_xunhuan)
            }
        }
    }


    override fun onPlaybackStageChange(stage: PlaybackStage) {
        val currentSong = stage.songInfo
        Log.e("qin", "onPlaybackStageChange")
        when (stage.stage) {
            PlaybackStage.PLAYING -> {
                mBinding.headTitle.headCenterTitle.text = currentSong?.songName
                mBinding.tvAuthorName.text = currentSong?.artist
                mBinding.tvSongName.text = currentSong?.songName
                mBinding.ivBofangDetail.setImageResource(R.mipmap.ic_pause)
            }

            PlaybackStage.PAUSE -> {
                mBinding.ivBofangDetail.setImageResource(R.mipmap.ic_bofang_detail)
            }

            PlaybackStage.ERROR -> {
                Log.e("Playback", "播放出错: ${stage.errorMsg}")
            }
        }
        EventUtils.sendEvent(BaseEvent(code = PLAY_STAUS_CHANGE, data = stage.stage))
    }

    // 格式化显示（示例：03:25/04:10）
    fun formatTime(millis: Long): String {
        val seconds = millis / 1000
        val minutes = seconds / 60
        val remainingSeconds = seconds % 60
        return String.format("%02d:%02d", minutes, remainingSeconds)
    }


    // 注册监听（通常在 onStart 或 onCreate 中）
    override fun onStart() {
        super.onStart()
        StarrySky.with().addPlayerEventListener(this, "PlayDetailActivity")
        startProgressUpdates() // 启动进度监听
    }

    // 取消监听（避免内存泄漏）
    override fun onStop() {
        super.onStop()
        progressJob?.cancel() // 取消协程
        StarrySky.with().removePlayerEventListener("PlayDetailActivity")

    }

    override fun onPlayProgress(currPos: Long, duration: Long) {
        // 获取当前播放位置（毫秒）

        mBinding.tvCurrentTime.text = formatTime(currPos).toString()
        // 获取音频总时长（毫秒）
        Log.e("qing", "视频总时长duration:" + duration)
        mBinding.tvCountTime.text = formatTime(duration).toString()
        val currentTime = currPos / 1000  // 转为秒
        val totalTime = duration / 1000
        Log.d("Progress", "当前进度: $currentTime/$totalTime 秒")

        // 更新 UI（如 SeekBar）
        mBinding.progressSeekbar.max = totalTime.toInt()
        mBinding.progressSeekbar.progress = currentTime.toInt()

    }

    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {

    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {
        when (type_proces) {
            "第一次插屏" -> {
                newGromoreFeedAd = NewGroMoreFeedAdManager(
                    this,
                    BaseAdConstants.FEEDAD_Id,
                    mBinding?.frameLayoutBannerDetail,
                    22
                )
                newGromoreFeedAd?.loadAd()
            }
        }
    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {

    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }


}


